package region

import (
	"context"
	"strings"
	"time"

	"mall/service/backend/common/enum/common"
	"mall/service/backend/common/errorx"
	"mall/service/backend/common/i18n"
	"mall/service/setting/model"
	"mall/service/setting/rpc/internal/svc"
	"mall/service/setting/rpc/internal/utils/errorhandler"
	"mall/service/setting/rpc/types/setting"

	"github.com/zeromicro/go-zero/core/logx"
)

type BackendUpdateRegionLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBackendUpdateRegionLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BackendUpdateRegionLogic {
	return &BackendUpdateRegionLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// group: region
func (l *BackendUpdateRegionLogic) BackendUpdateRegion(in *setting.RegionInfo) (*setting.BaseResp, error) {
	if in.Id == nil || *in.Id == 0 {
		return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
	}

	id := *in.Id

	region, err := l.svcCtx.SysRegion.FindOneNoCache(l.ctx, nil, id)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	// get parent level
	var regionLevel uint8
	if in.ParentId != nil && *in.ParentId != common.DefaultParentId {
		p, err := l.svcCtx.SysRegion.FindOne(l.ctx, *in.ParentId)
		if err != nil {
			return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
		}

		regionLevel = p.Level + 1
	} else {
		regionLevel = 1
	}

	region.Level = regionLevel
	if in.ParentId != nil {
		region.ParentID = *in.ParentId
	}
	if in.Sort != nil {
		region.Sort = uint16(*in.Sort)
	}
	if in.Name != nil {
		region.Name = strings.TrimSpace(*in.Name)

		if len(region.Name) == 0 {
			logx.Errorw("update region failed, its name is required")
			return nil, errorx.NewInvalidArgumentError("region.nameRequired")
		}
	}
	if in.Code != nil {
		region.Code = strings.TrimSpace(*in.Code)

		if len(region.Code) == 0 {
			logx.Errorw("update region failed, its code is required")
			return nil, errorx.NewInvalidArgumentError("region.codeRequired")
		}

		filterMap := make(map[string]map[string][]any)
		filterMap[model.SysRegionColumns.Code] = map[string][]any{
			"equalTo": []any{region.Code},
		}
		list, _, err := l.svcCtx.SysRegion.GetList(l.ctx, model.M{
			"pageSize": uint64(2),
			"select":   ",",
		}, -1, filterMap)
		if err != nil {
			return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
		}

		count := len(list)
		if count > 1 {
			return nil, errorx.NewAlreadyExistsError("region.codeAlreadyExists")
		}

		if count == 1 && list[0].ID != id {
			return nil, errorx.NewAlreadyExistsError("region.codeAlreadyExists")
		}
	}
	if in.Region != nil {
		region.Region = strings.TrimSpace(*in.Region)
	}
	if in.Status != nil {
		region.Status = uint8(*in.Status)
	}
	region.UpdatedAt = time.Now()
	err = l.svcCtx.SysRegion.Update(l.ctx, nil, region)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	return &setting.BaseResp{
		Msg: i18n.UpdateSuccess,
	}, nil
}
